package net.gagnat.android.trackit.activity;

import java.util.List;

import net.gagnat.android.trackit.R;
import net.gagnat.android.trackit.domain.LogTag;
import net.gagnat.android.trackit.service.LogTagsRepository;
import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;

public class ViewLogTags extends ListActivity {

	private static final int MENU_NEW_TAG = 0;
	private static final int DIALOG_ADD_NEW_TAG = 0;
	private ArrayAdapter<LogTag> adapter;
	private EditText newTagName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogTagsRepository.initialize(this);

		setContentView(R.layout.trackit_tag_list);

		List<LogTag> logTags = LogTagsRepository.getInstance().getLogTags();
		adapter = new ArrayAdapter<LogTag>(this, R.layout.trackit_tag_list_entry, R.id.tagName, logTags);
		setListAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_NEW_TAG, 0, getText(R.string.menu_new_tag)); //
		// .setIcon(android.R.drawable.ic_menu_add);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_NEW_TAG:
			showDialog(DIALOG_ADD_NEW_TAG);
			return true;
		default:
			return false;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
	    switch(id) {
	    case DIALOG_ADD_NEW_TAG:
	        dialog = createAddNewTagDialog();
	        break;
	    default:
	        dialog = null;
	    }
	    return dialog;
	}

	private Dialog createAddNewTagDialog() {
		Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.dialog_new_tag);
		dialog.setTitle("New tag");
		
		newTagName = (EditText) dialog.findViewById(R.id.newTagName);
		
		Button saveButton = (Button) dialog.findViewById(R.id.tagSaveButton);
		saveButton.setOnClickListener(saveButtonListener);

		return dialog;
	}

	private OnClickListener saveButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (newTagName != null) {
				LogTag newTag = new LogTag();
				newTag.setName(newTagName.getText().toString());
				LogTagsRepository.getInstance().saveTag(newTag);
				adapter.notifyDataSetChanged();
			}
		}
	};
}
